<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>支付宝扫码支付</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }
        body {
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }
        .container {
            max-width: 800px;
            margin: 50px auto;
            padding: 30px;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .header img {
            height: 40px;
            margin-bottom: 10px;
        }
        .header h1 {
            color: #1677ff;
            font-size: 24px;
            font-weight: 500;
        }
        .amount-section {
            margin-bottom: 30px;
        }
        .amount-section h2 {
            font-size: 18px;
            margin-bottom: 15px;
            color: #333;
            font-weight: 500;
        }
        .preset-amounts {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        .preset-amount {
            width: 23%;
            background-color: #f7f7f7;
            border: 1px solid #e8e8e8;
            border-radius: 6px;
            padding: 15px 0;
            text-align: center;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .preset-amount:hover {
            border-color: #1677ff;
            background-color: #f0f7ff;
        }
        .preset-amount.active {
            border-color: #1677ff;
            background-color: #f0f7ff;
            color: #1677ff;
        }
        .action-section {
            text-align: center;
            margin-top: 40px;
        }
        .pay-button {
            background-color: #1677ff;
            color: white;
            border: none;
            padding: 12px 40px;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .pay-button:hover {
            background-color: #0e5edb;
        }
        .payment-info {
            margin-top: 20px;
            margin-bottom: 20px;
            font-size: 14px;
            color: #666;
        }
        .alipay-logo {
            text-align: center;
            color: #1677ff;
            font-size: 40px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        /* 弹窗样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.6);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            visibility: hidden;
            opacity: 0;
            transition: visibility 0s linear 0.3s, opacity 0.3s;
        }
        .modal-overlay.active {
            visibility: visible;
            opacity: 1;
            transition-delay: 0s;
        }
        .modal-container {
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            width: 350px;
            max-width: 90%;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
            text-align: center;
        }
        .modal-title {
            font-size: 18px;
            margin-bottom: 20px;
            color: #333;
        }
        .qr-code-container {
            width: 250px;
            height: 250px;
            margin: 0 auto 20px;
            background-color: #f7f7f7;
            border: 1px solid #e8e8e8;
            border-radius: 6px;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
        }
        .close-modal {
            border: none;
            background-color: #f5f5f5;
            padding: 8px 20px;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            margin-top: 10px;
        }
        .modal-amount {
            font-size: 24px;
            color: #1677ff;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .loading-spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #1677ff;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        .payment-status {
            margin-top: 10px;
            font-size: 14px;
            color: #666;
        }
        .countdown {
            font-weight: bold;
            color: #1677ff;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                margin: 20px;
                padding: 20px;
            }
            .preset-amount {
                width: 48%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="alipay-logo">支付宝</div>
            <h1>扫码支付</h1>
        </div>
        
        <div class="amount-section">
            <h2>选择支付金额</h2>
            <div class="preset-amounts">
                <div class="preset-amount" data-amount="10">¥10</div>
                <div class="preset-amount" data-amount="50">¥50</div>
                <div class="preset-amount" data-amount="100">¥100</div>
                <div class="preset-amount" data-amount="500">¥500</div>
            </div>
        </div>
        
        <div class="action-section">
            <p class="payment-info" id="payment-info">当前未选择支付金额</p>
            <button class="pay-button" id="confirm-pay">确认支付</button>
        </div>
    </div>
    
    <!-- 弹窗组件 -->
    <div class="modal-overlay" id="qr-modal">
        <div class="modal-container">
            <h3 class="modal-title">支付宝扫码支付</h3>
            <div class="modal-amount" id="modal-amount">¥0.00</div>
            <div class="qr-code-container" id="qr-code-container">
                <div class="loading-spinner" id="loading-spinner"></div>
                <canvas id="qrcode-canvas" style="display: none;"></canvas>
            </div>
            <p>请使用支付宝APP，扫描二维码完成支付</p>
            <div class="payment-status" id="payment-status">
                等待支付... 自动检查支付状态中
            </div>
            <button class="close-modal" id="close-modal">关闭</button>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/qrcode-generator@1.4.4/qrcode.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const presetAmounts = document.querySelectorAll('.preset-amount');
            const confirmPayButton = document.getElementById('confirm-pay');
            const paymentInfo = document.getElementById('payment-info');
            const qrcodeCanvas = document.getElementById('qrcode-canvas');
            const qrModal = document.getElementById('qr-modal');
            const closeModal = document.getElementById('close-modal');
            const modalAmount = document.getElementById('modal-amount');
            const loadingSpinner = document.getElementById('loading-spinner');
            const paymentStatus = document.getElementById('payment-status');
            
            let selectedAmount = 0;
            let currentOrderNo = null;
            let paymentCheckInterval = null;
            
            // 预设金额点击事件
            presetAmounts.forEach(button => {
                button.addEventListener('click', function() {
                    const amount = parseFloat(this.getAttribute('data-amount'));
                    selectAmount(amount);
                    
                    // 清除所有预设金额的活跃状态
                    presetAmounts.forEach(btn => btn.classList.remove('active'));
                    
                    // 设置当前按钮为活跃状态
                    this.classList.add('active');
                });
            });
            
            // 确认支付按钮点击事件
            confirmPayButton.addEventListener('click', function() {
                if (selectedAmount > 0) {
                    // 清除之前的状态
                    if (paymentCheckInterval) {
                        clearInterval(paymentCheckInterval);
                        paymentCheckInterval = null;
                    }
                    
                    // 显示弹窗
                    qrModal.classList.add('active');
                    modalAmount.textContent = `¥${selectedAmount.toFixed(2)}`;
                    
                    // 显示加载状态
                    loadingSpinner.style.display = 'block';
                    qrcodeCanvas.style.display = 'none';
                    paymentStatus.innerHTML = '创建订单中...';
                    
                    // 请求后端接口获取二维码
                    createOrder(selectedAmount);
                } else {
                    alert('请先选择支付金额');
                }
            });
            
            // 关闭弹窗
            closeModal.addEventListener('click', function() {
                qrModal.classList.remove('active');
                // 清除轮询
                if (paymentCheckInterval) {
                    clearInterval(paymentCheckInterval);
                    paymentCheckInterval = null;
                }
            });
            
            // 选择金额
            function selectAmount(amount) {
                selectedAmount = amount;
                paymentInfo.textContent = `当前支付金额: ¥${amount.toFixed(2)}`;
            }
            
            // 请求后端创建订单接口
            function createOrder(amount) {
                // 使用相对路径，确保在任何环境下都能正确请求
                fetch('/pay/alipay/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `amount=${amount}`
                })
                .then(response => response.json())
                .then(data => {
                    // 隐藏加载状态
                    loadingSpinner.style.display = 'none';
                    
                    if (data.code === 200) {
                        // 生成二维码
                        generateQRCode(data.data.qrCode);
                        // 保存订单号，用于后续查询支付状态
                        currentOrderNo = data.data.orderNo;
                        // 开始轮询支付状态
                        startPaymentStatusCheck(currentOrderNo);
                        paymentStatus.innerHTML = '等待支付... 自动检查支付状态中';
                    } else {
                        alert('创建订单失败：' + data.message);
                        qrModal.classList.remove('active');
                    }
                })
                .catch(error => {
                    loadingSpinner.style.display = 'none';
                    console.error('创建订单异常:', error);
                    alert('创建订单异常，请稍后重试');
                    qrModal.classList.remove('active');
                });
            }
            
            // 开始轮询检查支付状态
            function startPaymentStatusCheck(orderNo) {
                if (paymentCheckInterval) {
                    clearInterval(paymentCheckInterval);
                }
                
                // 每3秒检查一次支付状态
                paymentCheckInterval = setInterval(() => {
                    checkPaymentStatus(orderNo);
                }, 3000);
                
                // 设置一个最长轮询时间，防止无限轮询
                setTimeout(() => {
                    if (paymentCheckInterval) {
                        clearInterval(paymentCheckInterval);
                        paymentStatus.innerHTML = '支付超时，请重新扫码支付或关闭后重试';
                    }
                }, 5 * 60 * 1000); // 5分钟后停止轮询
            }
            
            // 检查支付状态
            function checkPaymentStatus(orderNo) {
                fetch(`/pay/alipay/query?orderNo=${orderNo}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 200) {
                            const payStatus = data.data.payStatus;
                            
                            // 支付状态：0-未支付，1-支付成功
                            if (payStatus === 1) {
                                // 支付成功，清除轮询
                                if (paymentCheckInterval) {
                                    clearInterval(paymentCheckInterval);
                                    paymentCheckInterval = null;
                                }
                                
                                // 更新状态提示
                                paymentStatus.innerHTML = '<span style="color:#52c41a;font-weight:bold;">支付成功！</span> 正在跳转...';
                                
                                // 1秒后跳转到支付结果页
                                setTimeout(() => {
                                    // 关闭弹窗
                                    qrModal.classList.remove('active');
                                    
                                    // 跳转到支付结果页
                                    window.location.href = `/pay/result?orderNo=${data.data.orderNo}&tradeNo=${data.data.tradeNo}&amount=${data.data.amount}&payStatus=${payStatus}`;
                                }, 1000);
                            } else {
                                // 未支付，继续轮询
                                paymentStatus.innerHTML = '等待支付... 自动检查支付状态中';
                            }
                        }
                    })
                    .catch(error => {
                        console.error('查询支付状态异常:', error);
                        // 查询异常，但不停止轮询，只更新状态
                        paymentStatus.innerHTML = '查询支付状态异常，继续等待...';
                    });
            }
            
            // 生成二维码
            function generateQRCode(text) {
                // 使用 qrcode-generator 库生成二维码
                const qr = qrcode(0, 'M');
                qr.addData(text);
                qr.make();
                
                const moduleCount = qr.getModuleCount();
                const cellSize = Math.floor(200 / moduleCount);
                
                qrcodeCanvas.width = qrcodeCanvas.height = cellSize * moduleCount;
                const ctx = qrcodeCanvas.getContext('2d');
                
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(0, 0, qrcodeCanvas.width, qrcodeCanvas.height);
                
                ctx.fillStyle = '#000000';
                for (let row = 0; row < moduleCount; row++) {
                    for (let col = 0; col < moduleCount; col++) {
                        if (qr.isDark(row, col)) {
                            ctx.fillRect(col * cellSize, row * cellSize, cellSize, cellSize);
                        }
                    }
                }
                
                // 显示二维码
                qrcodeCanvas.style.display = 'block';
            }
        });
    </script>
</body>
</html> 